from flask import Flask, request, jsonify
from recognition_interface import recognition
from pydub import AudioSegment
from pydub.utils import mediainfo
import os
import wave
from aip import AipImageClassify
from flask_cors import CORS
from wenxin_api import translation, summarization


app = Flask(__name__)
app.config['MAX_CONTENT_LENGTH'] = 16 * 1024 * 1024

CORS(app) 

@app.route('/asr', methods=['POST'])
def asr():
    # 获取录音文件
    print('processing audio')
    audio = request.files['audio']
    # # # 执行Python方法进行处理
    
    # # # import pdb; pdb.set_trace()
    # audio.save('recording.m4a')

    # transcript = process_audio('recording.m4a', format='m4a')
    transcript = process_audio(audio, format='m4a')
    # import pdb; pdb.set_trace()
    # transcript = '我是谁'
    # print(transcript)
    output = jsonify({'transcription': transcript})
    # print(output.json)
    return output

@app.route('/summary', methods=['POST'])
def summary():
    # 从请求中获取转录结果数组
    data = request.get_json()
    transcriptions = data['transcriptions']
    merged_transcription = ' '.join(transcriptions)
 
    summary = summarization(merged_transcription, "direct")

    # 返回摘要结果
    return jsonify({'summary': summary})

@app.route('/summary_2', methods=['POST'])
def summary_2():
    # 从请求中获取转录结果数组
    data = request.get_json()
    transcriptions = data['transcriptions']
    transcriptions_2 = data['transcriptions_2']
    sequence = data['sequence']
    idx_1 = 0
    idx_2 = 0
    merged_transcription = ' '
    for seq in sequence:
        if int(seq) == 0:
            merged_transcription += '甲："' + transcriptions[idx_1] + '"\n'
            idx_1 += 1
        elif int(seq) == 1:
            merged_transcription += '乙："' + transcriptions[idx_2] + '"\n'
            idx_2 += 1
    summary = summarization(merged_transcription, "direct")

    # 返回摘要结果
    return jsonify({'summary': summary})

@app.route('/translation', methods=['POST'])
def translation():
    # 从请求中获取转录结果数组
    data = request.get_json()
    transcriptions = data['transcriptions']
    merged_transcription = ' '.join(transcriptions)
 
    translation = translation(merged_transcription, "en")

    # 返回摘要结果
    return jsonify({'translation': translation})

def process_audio(audio, format, is_file=False):
    return recognition(audio, format=format, is_file=is_file)

if __name__ == '__main__':
    app.run(debug=True, port=5000)
    # app.run(port=5000)